package com.bcx.crm.plat.listener;

import com.bcx.crm.plat.core.utils.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * Created by ys on 2018/1/21.
 */
/**
 * 如果在上下文部署一个实现了ApplicationListener接口的bean
 * 那么每当在一个ApplicationEvent发布到ApplicationContext时,这个bean得到通知
 * 其实这就是标准的观察者observer设计模式
 * 获取所有的@RequestMapping路径信息:ServletUtils.getApplicationContext().getBean(RequestMappingHandlerMapping.class).getHandlerMethods()
 */

/**
 * ApplicationEvent是父类,子类:ContextClosedEvent,ContextRefreshedEvent,ContextStartedEvent,ContextStoppedEvent,RequestHandleEvent
 */
@Component
public class ApplicationEventListener implements ApplicationListener<ApplicationEvent> {

    private static Logger logger = LoggerFactory.getLogger(ApplicationEventListener.class);
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ContextRefreshedEvent){  //上下文刷新事件(上下文包含多个事件)--spring上下文启动
            if (null == ((ContextRefreshedEvent) event).getApplicationContext().getParent()){
                if (logger.isInfoEnabled()){
                    logger.info("spring初始化完成");
                }
            }else {
                if (logger.isInfoEnabled()){
                    logger.info("springMvc环境初始化完成");
                    ServletUtils.setApplicationContext(((ContextRefreshedEvent) event).getApplicationContext());
                }
            }
        }
    }
}
